必須實作的接口
type Chaincode interface
{
//初始化
Init(stub ChaincodeStubInterface) pb.Response
//查詢或更新 world state
Invoke(stub ChaincodeStubInterface) pb.Response
}
撰寫範例
package main
import
(
"errors"
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
type SimpleChaincode struct { }
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, funcGon string, args []string) ([]byte, error)
{
//…
}
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, funcGon string, args []string) ([]byte, error)
{
//…
}
func main()
{
err := shim.Start(new(SimpleChaincode))
if err != nil
{
fmt.Prinn("Error starGng Simple chaincode: %s", err)
}
}
以 fabric chaincode_example02 為例:
啟動 Orderer 節點
orderer
啟動 peer
CORE_PEER_ID=peer0 peer node start
設置 chaincode
peer chaincode install -p [鏈碼路徑] -n [檔案名稱] -v 1.0
peer chaincode install -p github.com/hyperledger/fabric/examples/chaincode/go/
chaincode_example02/ -n mycc -v 1.0
測試 chaincode:測試模式可以使用 Rest 通訊協定、而正式模式只能使用 Node.js 客戶端
peer chaincode instanGate -n mycc -v 1.0 -c '{"Args": ["init", "A", "100", "B", "100"]}'
peer chaincode invoke -n mycc -c '{"Args":["invoke", "A", "B", "10"]}'
peer chaincode query -n mycc -c '{"Args":["query", "A"]}'
shim.ChaincodeStubInterface
GetState(key string) ([]byte, error)
PutState(key string, value []byte) error
DelState(key string) error
GetStateByRange(startKey, endKey string) (StateQueryIteratorInterface, error)
GetStateByPartialCompositeKey(objectType string, keys []string) (StateQueryIteratorInterface, error)
GetQueryResult(query string) (StateQueryIteratorInterface, error)
GetHistoryForKey(key string) (StateQueryIteratorInterface, error)
CreateCompositeKey(objectType string, a,ributes []string) (string, error)
SplitCompositeKey(compositeKey string) (string, []string, error)
GetArgs() [][]byte
GetStringArgs() []string
GetFuncGonAndParameters() (string, []string)
GetArgsSlice() ([]byte, error)
GetCreator() ([]byte, error)
GetTransient() (map[string][]byte, error)
GetBinding() ([]byte, error)
GetTxTimestamp() (*Gmestamp.Timestamp, error)
GetTxID() string
SetEvent(name string, payload []byte) error
Start(cc Chaincode) error //註冊 Chaincode
InvokeChaincode(chaincodeName string, args [][]byte, channel string) pb.Response
NewLogger(name string) *ChaincodeLogger //建立 Logger
SetLoggingLevel(level LoggingLevel) //設定 Log 訊息輸出等級
API 線上文件:
https://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim
Postman Rest API 測試工具:
https://www.getpostman.com/